package tms.controler;

import java.util.Observable;
import java.util.Observer;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import tms.Cache;
import tms.model.Account;
import tms.view.WelcomeView;

/**
 * This is intended to manage the changing panel methods.
 * BaseController is implemented using Singleton patterns
 */
public class BaseController implements IController, Observer {

    private static BaseController instance;
    private WelcomeView view;
    private JPanel dynamicPanel;

    public static BaseController getInstance() {
        if (instance == null) {
            instance = new BaseController();
        }
        return instance;
    }

    public void logout() {
        int answer = JOptionPane.showConfirmDialog(
                view, "Do you want to logout?", "Logout", JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            Cache.setCurrentUser(null);
        }
    }

    public void showSearchFlightView() {
        // show search flight view
        SearchController sfc = new SearchController();
        sfc.createView();
        changeToPanel(sfc.getView());
    }

    /**
     * Replace the current changeable panel with target.
     * @param target
     */
    public void changeToPanel(JPanel target) {
        dynamicPanel.removeAll();
        dynamicPanel.add(target);
        dynamicPanel.repaint();
        view.validate();
    }

    public void createView() {
        view = new WelcomeView();
        Cache.addObserver(this);

        this.dynamicPanel = view.getDynamicPanel();

        showSearchFlightView();
    }

    public Object getView() {
        if (view == null) {
            createView();
        }
        return view;
    }

    public void update(Observable obs, Object obj) {
        if (obj != null) {
            view.hideLoginStuffs();
            view.setMenuUserCaption("Hello, " + ((Account) obj).getFullName());
        } else {
            view.hideLogoutStuffs();
            view.setMenuUserCaption("");
        }
    }
}
